<?php

if (!function_exists('build_ranstr')) {
    /**
     * 获得随机字符串
     * @param   Number  $len    需要的长度
     * @param   Bool    $special    是否需要特殊符号
     * @return  String  返回随机字符串
     */
    function build_ranstr($len = 8, $special = false)
    {
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );

        if ($special) {
            $chars = array_merge($chars, array(
                "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
                "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
                "}", "<", ">", "~", "+", "=", ",", "."
            ));
        }

        $charsLen = count($chars) - 1;
        shuffle($chars); //打乱数组顺序
        $str = ''; // 用来拼接的
        for ($i = 0; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
        }
        return $str;
    }
}

if(!function_exists('showMsg'))
{
    /**
     * 跳转提示函数
     * @param String $msg 提示信息
     * @param String $url 跳转地址
    */
    function showMsg($msg,$url = null)
    {
        $str = '';

        if($url)
        {
            $str = "<script>
                alert('$msg');
                location.href = '$url';
            </script>";
        }else{
            $str = "<script>
                alert('$msg');
                history.go(-1);
            </script>";
        }

        echo $str;
        exit;
    }
}

if(!function_exists('find'))
{
    /**
     * 查询单条数据
     * @param String $sql Sql语句
    */
    function find($sql)
    {
        // 声明全局变量
        global $conn;

        // 存放查询出来的数据
        $data = [];

        $result = mysqli_query($conn,$sql);

        if($result && mysqli_num_rows($result) > 0)
        {
            $data = mysqli_fetch_assoc($result);
        }

        return $data;

    }
}

if(!function_exists('all'))
{
    /**
     * 查询多条数据
     * @param String $sql Sql语句
    */
    function all($sql)
    {
        global $conn;

        $list = [];

        $result = mysqli_query($conn,$sql);

        if($result && mysqli_num_rows($result) > 0)
        {
            while($data = mysqli_fetch_assoc($result))
            {
                $list[] = $data;
            }
        }

        return $list;
    }
}


if(!function_exists('checkAuth'))
{
    /**
     * 验证是否登录
    */
    function checkAuth()
    {
        $LoginAdmin = isset($_COOKIE['LoginAdmin']) ? json_decode($_COOKIE['LoginAdmin'],true) : [];

        if(!$LoginAdmin)
        {
            showMsg('请登录','login.php');
        }

        $id = $LoginAdmin['id'] ?? 0;
        $username = $LoginAdmin['username'] ?? '';

        $admin = find("SELECT * FROM `pre_admin` WHERE `id` = '$id' AND `username` = '$username'");

        if(!$admin)
        {
            setcookie('LoginAdmin','',time() - 1);
            showMsg('非法登录','login.php');
        }

        $data = [
            'id' => $admin['id'],
            'username' => $admin['username'],
            'avatar' => $admin['avatar']
        ];

        // 更新cookie
        setcookie('LoginAdmin',json_encode($data));

        // 返回查询信息给视图调用
        return $data;
    }
}

if(!function_exists('build_upload'))
{
    /**
     * 单图上传
     * @param String $name 图片名称
     * @param String $path 保存路径
     * @param Array  $type 图片格式
     * @param Int    $size 图片大小
     * @return Array 返回结果
    */
    function build_upload($name,$path = 'uploads',$type = ['jpg','png','jpeg','gif'],$size = 1048576)
    {
        // 判断指定的保存文件夹是否不存在，如果不存在就创建文件夹
        if(!is_dir($path))
        {
            mkdir($path);
        }

        // 返回结果的数组
        $result = [
            'code' => 0,
            'msg' => '未知信息',
            'data' => null,
        ];

        // 获取上传错误信息
        $ErrorCode = $_FILES[$name]['error'];

        switch($ErrorCode)
        {
            case 1:
                $result['msg'] = '上传大小不能超过upload_max_filesize设置的值';
                return $result;

            case 2:
                $result['msg'] = '上传大小不能超过MAX_FILE_SIZE设置的值';
                return $result;

            case 3:
                $result['msg'] = '图片上传不完整';
            
            case 4:
                $result['msg'] = '请选择图片';
                return $result;
        }

        // 获取图片后缀
        $ext = pathinfo($_FILES[$name]['name'],PATHINFO_EXTENSION);

        if(!in_array($ext,$type))
        {
            $result['msg'] = '上传图片格式错误';
            return $result;
        }

        // 判断图片大小
        $fileSize = $_FILES[$name]['size'];

        if($fileSize > $size)
        {
            $result['msg'] = '图片过大，请压缩后上传';
            return $result;
        }

        // 设置图片保存后的名称
        $fileName = date('YmdHis',time()) . mt_rand(1000,9999) . mt_rand(1000,9999) . '.' . $ext;

        // 判断图片是否通过http post 上传
        if(is_uploaded_file($_FILES[$name]['tmp_name']))
        {
            $res = @move_uploaded_file($_FILES[$name]['tmp_name'],$path . '/' . $fileName);

            if($res === true)
            {
                $result = [
                    'code' => 1,
                    'msg' => '图片上传成功',
                    'data' => '/' . $path . '/' . $fileName
                ];
            }else{
                $result['msg'] = '图片上传失败';
            }

        }else{
            $result['msg'] = '图片上传错误';
        }

        return $result;
    }
}

if(!function_exists('add'))
{
    /**
     * 添加数据
     * @param String $table 表名
     * @param Array  $data  插入数据
     * @param String $prefix 表前缀
    */
    function add($table,$data,$prefix = 'pre_')
    {
        // 声明全局变量
        global $conn;

        // 拼接表名
        $table = "`" . $prefix . $table . "`";

        // 获取$data的key
        $keys = array_keys($data);

        $fields = "`" . implode("`,`",$keys) . "`";

        $values = "'" . implode("','",$data) . "'";

        // 组装sql语句
        $sql = "INSERT INTO $table($fields)VALUES($values)";

        $res = mysqli_query($conn,$sql);

        if(!$res)
        {
            return ['code' => 0,'msg' => mysqli_error($conn)];
        }

        return ['code' => 1,'msg' => '添加成功','data' => mysqli_insert_id($conn)];
    }
}

if(!function_exists('getUrl'))
{
    /**
     * 重组当前url
    */
    function getUrl()
    {
        // 获取当前完整的地址
        $url = $_SERVER['PHP_SELF'] . '?';

        if(!empty($_GET))
        {
            foreach($_GET as $key => $val)
            {
                if($key != 'page')
                {
                    $url .= $key . '=' . $val . '&';
                }
            }
        }

        return $url;
    }
}

if(!function_exists('showPage'))
{
    /**
     * 分页
     * @param String $current 当前页
     * @param String $count   数据记录总数
     * @param Int    $limit   每页显示多少条数据
     * @param Int    $size    页码
     * @param String $class   分页样式
    */
    function showPage($current, $count,$limit,$size,$class = 'digg')
    {
        // 定义空的字符串 用来的拼接分页结构
        $page = '';

        // 如果数据总数大于每页显示数据时就会出现分页
        if($count > $limit)
        {
            // 获取总分页
            $pageCount = ceil($count / $limit);

            // 获取地址
            $url = getUrl();

            // 开始拼接
            $page .= '<div class="'. $class .'">';

            // 首页以及上一页
            if($current == 1)
            {
                $page .= '<span class="disabled">首&nbsp;页</span>';
                $page .= '<span class="disabled">上一页</span>';
            }else{
                $page .= '<a href="'. $url .'page=1">首&nbsp;页</a>';
                $page .= '<a href="'. $url .'page='. ($current - 1) .'">上一页</a>';
            }

            // 计算中间页逻辑
            /* 
                [1] 2 3 4 5
                1 [2] 3 4 5
                1 2 [3] 4 5
                1 2 3 [4] 5
                
            */

            if($current <= floor($size / 2))
            {
                // 当前页在中间位置靠左,floor()向下取整
                $start = 1;

                // 如果总页数大于中间显示多少页,结束数字就是中间显示多少页的数字,否则结束数字就是总页数
                $end = $pageCount < $size ? $pageCount : $size;
            }elseif($current >= $pageCount - floor($size / 2))
            {
                // 当前页在中间位置靠右 避免页数出现0或者负数
                $start = $pageCount - $size + 1 <= 0 ? 1 : $pageCount - $size + 1;
                $end = $pageCount;
            }else{
                $start = $current - floor($size / 2);
                $end = $current + floor($size / 2);
            }

            for($i = $start;$i <= $end;$i++)
            {
                if($i == $current)
                {
                    $page .= '<span class="current">' . $i . '</span>';
                }else{
                    $page .= '<a href="'. $url .'page='. $i .'">' . $i . '</a>';
                }
            }


            // 尾页以及下一页
            if($current == $pageCount)
            {
                $page .= '<span class="disabled">下一页</span>';
                $page .= '<span class="disabled">尾&nbsp;页</span>';
            }else{
                $page .= '<a href="'. $url .'page='. ($current + 1) .'">下一页</a>';
                $page .= '<a href="'. $url .'page='. $pageCount .'">尾&nbsp;页</a>';
            }


            // 结束
            $page .= '</div>';
        }

        return $page;
    }
}


if(!function_exists('update'))
{
    /**
     * 更新数据
     * @param String $table 表名
     * @param Array  $data  更新数据
     * @param String $where 更新条件
     * @param String $prefix 表前缀
    */
    function update($table,$data,$where = 1,$prefix = 'pre_')
    {
        global $conn;

        $table = "`" . $prefix . $table . "`";

        // 组装SQL语句
        $str = '';

        foreach($data as $key => $val)
        {
            $str .= "`" . $key ."` = '" . $val ."',";
        }

        $str = rtrim($str,',');

        $sql = "UPDATE $table SET $str WHERE $where";

        $res = mysqli_query($conn,$sql);

        if(!$res)
        {
            return ['code' => 0,'msg' => mysqli_error($conn)];
        }

        return ['code' => 1,'msg' => '编辑成功','data' => mysqli_affected_rows($conn)];
    }
}


if(!function_exists('del'))
{
    /**
     * 删除数据
     * @param String $table 表名
     * @param String $where 删除条件
     * @param String $prefix 表前缀
    */
    function del($table,$where = 1,$prefix = 'pre_')
    {
        global $conn;

        $table = '`' . $prefix . $table . '`';

        $sql = "DELETE FROM $table WHERE $where";

        $res = mysqli_query($conn,$sql);

        if(!$res)
        {
            return ['code' => 0,'msg' => mysqli_error($conn)];
        }

        return ['code' => 1,'msg' => '删除成功','data' => mysqli_affected_rows($conn)];
    }
}